import BaseAudioPlayer from "@/common/audio/BaseAudioPlayer";
import { MediaStatus } from "@/common/const";
import type { Station } from "../types/interface";

export default class AppAudioPlayer extends BaseAudioPlayer {
	private audioCtx = uni.getBackgroundAudioManager();
	private currentRadio: Station | null = null;
	private isInitialWaiting = false;
	private retryCount = 0;
	private maxRetries = 3;

	constructor() {
		super();
		this.audioCtx.title = '默认标题';
		this.audioCtx.epname = '默认节目';
		this.audioCtx.coverImgUrl = 'https://c-ssl.duitang.com/uploads/item/201803/17/20180317200156_qpcds.jpg';
		this.bindEvents();
	}

	private bindEvents() {
		this.audioCtx.onPlay(() => {
			this.setStatus(MediaStatus.playing);
			this.retryCount = 0; // 播放成功时重置重试计数
		});

		this.audioCtx.onPause(() => this.setStatus(MediaStatus.paused));
		this.audioCtx.onStop(() => this.setStatus(MediaStatus.stoped));
		this.audioCtx.onEnded(() => this.setStatus(MediaStatus.stoped));

		this.audioCtx.onWaiting(() => {
			this.setStatus(MediaStatus.waiting);
			// 👉 智能等待判断
			if (!this.isInitialWaiting && this.currentRadio && this.retryCount < this.maxRetries) {
				this.retryPlay(this.currentRadio);
			}
		});

		this.audioCtx.onError((err) => {
			this.setStatus(MediaStatus.error);
			console.log("error:", err?.errCode || err?.code);
		});
	}

	private retryPlay(radio: Station) {
		this.retryCount++;
		console.log(`🔁 重试播放：第 ${this.retryCount} 次`);

		// 可以适当延迟重试
		setTimeout(() => {
			this.audioCtx.src = radio.url;
			this.audioCtx.play();
		}, 1500);
	}

	play(radio: Station) {
		this.currentRadio = radio;
		this.isInitialWaiting = true;
		this.retryCount = 0;

		this.audioCtx.title = radio.name;
		this.audioCtx.coverImgUrl = radio.favicon;
		this.audioCtx.src = radio.url;
		this.audioCtx.play();

		// ⏳设定初始缓冲窗口（避免刚开始播放时误触重试）
		setTimeout(() => {
			this.isInitialWaiting = false;
		}, 3000);
	}

	pause() {
		this.audioCtx.pause();
		this.audioCtx.src = 'invalid';
		this.setStatus(MediaStatus.paused);
	}

	stop() {
		this.audioCtx.src = 'invalid';
		this.audioCtx.stop();
		this.setStatus(MediaStatus.stoped);
		this.currentRadio = null;
	}
}
